
package com.android.formula.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.android.formula.R;
import com.android.formula.model.FormulaNote;
import com.android.formula.model.TypeFormula;
import com.android.formula.task.GetNoteFormulaDBTask;
import com.android.formula.task.IDataEventHandler;
import com.android.formula.task.SetNoteDBTask;
import com.android.formula.task.SetTypeFormulaDBTask;
import com.android.formula.utils.CommonUtils;
import com.android.formula.utils.Constants;
import com.google.android.gms.ads.AdListener;

public class EditNoteActivity extends BaseActivity implements TextWatcher {
    private static int RESULT_LOAD_IMG = 1;

    private EditText mNoteNameEdt;

    private EditText mDescriptionEdt;

    private ImageView mNoteImg;

    private Button mImgBrowseBtn;

    private Button mSaveBtn;

    private Button mCancelBtn;

    private String imgDecodableString;

    private FormulaNote mFormulaNote;

    private TypeFormula mTypeFormula;

    private ScrollView mScrollView;

    @Override
    public void initView() {
        setContentView(R.layout.activity_edit_note);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        mNoteNameEdt = (EditText) findViewById(R.id.edit_note_edt_name);
        mNoteNameEdt.addTextChangedListener(this);
        mDescriptionEdt = (EditText) findViewById(R.id.edit_note_edt_des);
        mDescriptionEdt.addTextChangedListener(this);

        mNoteImg = (ImageView) findViewById(R.id.edit_note_img);

        mImgBrowseBtn = (Button) findViewById(R.id.edit_note_btn_browse_img);
        mImgBrowseBtn.setOnClickListener(this);
        mSaveBtn = (Button) findViewById(R.id.edit_note_btn_save);
        mSaveBtn.setOnClickListener(this);
        mCancelBtn = (Button) findViewById(R.id.edit_note_btn_cancel);
        mCancelBtn.setOnClickListener(this);

        mScrollView = (ScrollView) findViewById(R.id.edit_note_scrollview);

        initData();
        setAdListener();
    }

    private void initData() {
        Bundle bun = getIntent().getExtras();
        mTypeFormula = (TypeFormula) bun.getSerializable(Constants.DATA_KEY);

        if (mTypeFormula != null) {
            mNoteNameEdt.setText(mTypeFormula.getTypeName());
            new GetNoteFormulaDBTask(this, mTypeFormula, new IDataEventHandler<FormulaNote>() {

                @Override
                public void onNotifyNoData() {
                }

                @Override
                public void onNotifyErrorMessage(String title, String message) {
                }

                @Override
                public void onNotifyData(FormulaNote data) {
                    if (data != null) {
                        mFormulaNote = data;
                        mDescriptionEdt.setText(data.getFormulaDes());
                        imgDecodableString = data.getFormulaImg();
                        mNoteImg.setImageBitmap(CommonUtils.decodeBitmap(EditNoteActivity.this,
                                data.getFormulaImg()));
                    }
                }
            }).execute(mTypeFormula);
        } else {
            finish();
        }
    }

    @Override
    public void loadDataScreen() {
    }

    @Override
    public void onClickWithDelay(View v) {
        switch (v.getId()) {
            case R.id.edit_note_btn_browse_img:
                pickImageFromGallery();
                break;
            case R.id.edit_note_btn_save:
                saveNote();
                break;
            case R.id.edit_note_btn_cancel:
                finish();
                break;
            default:
                break;
        }
    }

    private void pickImageFromGallery() {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = {
                    MediaStore.Images.Media.DATA
                };

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null,
                        null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();
                // Set the Image in ImageView after decoding the String
                mNoteImg.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));

            } else {
                Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
            mNoteImg.setImageResource(R.drawable.no_image);
        }

    }

    private void saveNote() {
        setAutoHideKeyboard(mNoteNameEdt);
        setAutoHideKeyboard(mDescriptionEdt);
        saveTypeFormula();
    }

    private void saveTypeFormula() {
        if (!TextUtils.equals(mTypeFormula.getTypeName(), mNoteNameEdt.getText().toString())) {
            Log.i("aa", "saveTypeFormula changed");
            mTypeFormula.setTypeName(mNoteNameEdt.getText().toString());
            new SetTypeFormulaDBTask(this, mTypeFormula, null, new IDataEventHandler<Integer>() {

                @Override
                public void onNotifyData(Integer data) {
                    // save note
                    saveFormula();
                }

                @Override
                public void onNotifyNoData() {
                }

                @Override
                public void onNotifyErrorMessage(String title, String message) {
                }
            }).execute(mTypeFormula);
        } else {
            Log.i("aa", "saveTypeFormula not changed");
            saveFormula();
        }
    }

    private void saveFormula() {
        if (!TextUtils.equals(mFormulaNote.getFormulaDes(), mDescriptionEdt.getText().toString())
                || (!TextUtils.equals(mFormulaNote.getFormulaImg(), imgDecodableString))) {
            Log.i("aa", "saveFormula changed");
            mFormulaNote.setFormulaDes(mDescriptionEdt.getText().toString());
            mFormulaNote.setFormulaImg(imgDecodableString);
            mFormulaNote.setTypeId(mTypeFormula.getTypeId());

            new SetNoteDBTask(this, mFormulaNote, null, new IDataEventHandler<Integer>() {

                @Override
                public void onNotifyNoData() {
                }

                @Override
                public void onNotifyErrorMessage(String title, String message) {
                }

                @Override
                public void onNotifyData(Integer data) {
                    finish();
                }
            }).execute(mFormulaNote);
        } else {
            Log.i("aa", "saveFormula not changed");
            finish();
        }
    }

    private void checkEnableBtnSave() {
        if (!TextUtils.isEmpty(mNoteNameEdt.getText().toString().trim())
                && !TextUtils.isEmpty(mDescriptionEdt.getText().toString().trim())) {
            mSaveBtn.setEnabled(true);
        } else {
            mSaveBtn.setEnabled(false);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        checkEnableBtnSave();
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void setAdListener() {
        final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        mAdListener = new AdListener() {
            @Override
            public void onAdFailedToLoad(int errorCode) {
                super.onAdFailedToLoad(errorCode);
                mAdView.setVisibility(View.GONE);
            }

            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                mAdView.setVisibility(View.VISIBLE);
                params.addRule(RelativeLayout.ABOVE, R.id.edit_note_layout_ads);
                params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
                mScrollView.setLayoutParams(params);
            }
        };
    }
}
